package com.example.camera2application;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback {


    private SurfaceHolder holder;
    private MyThread myThread;

    public MySurfaceView(Context context) {
        super(context);
    }

    public MySurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MySurfaceView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public MySurfaceView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    private void init(){
        holder = getHolder();
        myThread = new MyThread(holder);
    }


    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        myThread.isRun = true;
        myThread.start();

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {


    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        myThread.isRun = false;
    }

    private static class MyThread extends Thread{
        public boolean isRun;
        private SurfaceHolder holder;
        public MyThread(SurfaceHolder holder){
            isRun = true;
            this.holder = holder;

        }
        @Override
        public void run() {
            int counter = 0;
            Canvas canvas = null;
            while (isRun){
                canvas = holder.lockCanvas();
                canvas.drawColor(Color.WHITE);
                Paint p = new Paint();
                p.setColor(Color.BLACK);
                p.setTextSize(30);
                Rect rect = new Rect(100,50,380,330);
                canvas.drawRect(rect,p);
                canvas.drawText("Interval = "+(counter++)+"seconds",100,410,p);

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    holder.unlockCanvasAndPost(canvas);
                }
            }
        }
    }
}
